package cn.jekun.web.shop.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.TsAccount;
import cn.jekun.component.core.service.AccountPayService;
import cn.jekun.web.shop.bean.BanksAccount;
import cn.jekun.web.shop.service.AccountService;
import cn.jekun.web.shop.service.BanksService;

/**
 * 提现(商家网页版后台)
 * @author yuan
 *
 */
public class WithdrawAction extends ShopBaseAction{
	private static final String AUTH_SHOP_MY_ACCOUNT_SETTLE="SHOP_MY_ACCOUNT_SETTLE";//提现
	
	@Resource(name=AccountService.BEAN_NAME)
	AccountService accountService;
	
	@Resource(name = BanksService.BEAN_NAME)
	BanksService banksService;
	
	@Resource(name = AccountPayService.BEAN_NAME)
	AccountPayService accountPayService;

	/**
	 * 提现
	 * @return
	 */
	public String withdraw(){
		JSONObject jsonObject=new JSONObject();
		
		try {
			//获取账户余额
			String shopId=this.getSessionUser().getShopId();
			JSONObject jsonAccountObject=accountPayService.querySettleAmount("", shopId,Constants.TS_ACCOUNT_OWNER_TYPE.SHOP);
			String code=jsonAccountObject.getString("code");
			if(code.equals("0")){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有找到商家支付账户。");
				return this.writeJson(jsonObject);
			}
			String settleAmount=jsonAccountObject.getString("settleAmount");//可提现
			Double settleAmountDouble=new Double(settleAmount);
			
			String balance=jsonAccountObject.getString("balance");//余额
			Double balanceDouble=new Double(balance);
			
			java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
			nf.setGroupingUsed(false); 
			nf.setMinimumFractionDigits(3);
			
			//最低提现金额
			double min = cn.jekun.component.core.service.AccountService.getMin();
			int days = cn.jekun.component.core.service.AccountService.getDays();
			int maxTimes = cn.jekun.component.core.service.AccountService.getMaxTimes();
			
			jsonObject.put("min",nf.format(min)) ;//最低提现金额
			
			String tips = "提现免手续费,约1-3个工作日到账";
			if(min>0){
				tips += ",最低提现"+min+"元";
			}
			if(days >0 && maxTimes >0){
				tips += ",每"+days+"天最多提现"+maxTimes+"次";
			}
			tips+="。";
			
			jsonObject.put("tips",tips) ;//
			
			jsonObject.put("isSetPay",jsonAccountObject.getString("isSetPay")) ;//是否已经设置了支付密码
			jsonObject.put("balance",balanceDouble==null?"0.00":nf.format(balanceDouble)) ;
			jsonObject.put("settleAmount",settleAmountDouble==null?"0.00":nf.format(settleAmountDouble));
			//获取结算银行卡号
			BanksAccount banksAccount = null;
			try{
				banksAccount = this.banksService.getBankAccount();
				
				if(banksAccount!=null){
					banksAccount.setBankNumber(EncryptUtil.getBankNumber(banksAccount.getBankNumber()));
					jsonObject.put("bankNumber",banksAccount.getBankNumber()==null?"":banksAccount.getBankNumber());
					jsonObject.put("bankName",banksAccount.getBankName()==null?"":banksAccount.getBankName());
					jsonObject.put("accountId",banksAccount.getAccountId()==null?"":banksAccount.getAccountId());
					jsonObject.put("accountName",banksAccount.getAccountName()==null?"":banksAccount.getAccountName());
					jsonObject.put("bankNumber_sort",EncryptUtil.getBankNumber(banksAccount.getBankNumber()));//银行帐号转换*号
					
					//验证次数
					JSONObject validateResult = accountPayService.validateMaxTimes(banksAccount.getAccountId());
					if (!"1".equals(validateResult.get("code"))) {
						jsonObject.put("code", "-1");
						jsonObject.put("message", validateResult.get("message"));
						return this.writeJson(jsonObject);
					}
				}
			}catch(Exception e){
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"请先绑定提现银行卡。只能有1个默认的提现账户。");
				return this.writeJson(jsonObject);
			}
			if (banksAccount == null) {
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有绑定提现银行卡号，请先绑定提现银行卡。");
				return this.writeJson(jsonObject);
			}
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}
	/**
	 * 提现申请
	 * @return
	 */
	public String settleApply(){
		JSONObject jsonObject=new JSONObject();
		
		String accountId = request.getParameter("accountId");//提现账户代码
		String bankNumber = request.getParameter("bankNumber");//银行账户
		String bankName = request.getParameter("bankName");//银行名称
		String accountName = request.getParameter("accountName");//账户姓名
		String amountStr = request.getParameter("amount");//提现金额
		String paypwd = request.getParameter("paypwd");//支付密码
		String _sign_key = request.getParameter("_sign_key");//加密
		
		if (StringUtils.isBlank(accountId)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请选择提现的银行账户");
			return this.writeJson(jsonObject);
		}
		if (StringUtils.isBlank(paypwd)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请输入支付密码");
			return this.writeJson(jsonObject);
		}
		//检查提现金额
		if (StringUtils.isBlank(amountStr)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请输入提现的金额");
			return this.writeJson(jsonObject);
		}
		double amount = 0;
		try {
			amount = Double.parseDouble(amountStr);
		} catch (Exception e) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，提现金额必须是有效的数字");
			return this.writeJson(jsonObject);
			
		}
		if(amount <=0){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，提现金额必须大于0");
			return this.writeJson(jsonObject);
		}
		if (StringUtils.isBlank(bankNumber)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法银行账户");
			return this.writeJson(jsonObject);
		}
		if (StringUtils.isBlank(bankName)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法银行名称");
			return this.writeJson(jsonObject);
		}
		if (StringUtils.isBlank(accountName)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法账户姓名");
			return this.writeJson(jsonObject);
		}
		String md5 = EncryptUtil.md5(accountId+amountStr+bankNumber+bankName+accountName+paypwd);
		if (!md5.equals(_sign_key)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"非法提交");
			return this.writeJson(jsonObject);
		}
		
		//获取账户信息
		String shopId=this.getSessionUser().getShopId();
		TsAccount tsAccount = this.accountService.one(shopId);
		if(tsAccount == null){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，没有找到商家支付账户。");
			return this.writeJson(jsonObject);
		}
		//提现申请
		String settleApplyId = null;//提现申请代码
		try{
			JSONObject jsonSettleApply=this.accountPayService.settleApply("", tsAccount.getAccountId(), amount+"", "",accountId, paypwd,Constants.SG_APPLY_TYPE.SHOP_WEB,this.getUserId());
			String code=jsonSettleApply.getString("code");
			String message=jsonSettleApply.getString("message");
			
			if(code.equals("0")){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,message);
				return this.writeJson(jsonObject);
			}
			
			settleApplyId=jsonSettleApply.getString("applyId");
			
			//settleApplyId = this.banksService.settleApply(this.getSessionUser().getUserId(),accountId, amount,fee,paypwd);
			this.logService.addShopAuditLog(AUTH_SHOP_MY_ACCOUNT_SETTLE, "申请提现成功，提现申请代码:"+settleApplyId);//记录操作日志
		}catch(Exception e){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"增加提现申请发生错误:"+e.getMessage());
			return this.writeJson(jsonObject);
		}
		if(settleApplyId == null){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"增加提现申请失败");
			return this.writeJson(jsonObject);
		}
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"申请成功,请等待银行处理");
		
		return this.writeJson(jsonObject);
		
	}
	
	/**
	 * 提现记录
	 * @return
	 */
	public String querySettle(){
		
		
		JSONObject jsonObject=new JSONObject();
		
		
		try {
			
			String beginMoney=request.getParameter("beginMoney");
			String endMoney=request.getParameter("endMoney");
			String beginDate=request.getParameter("beginDate");
			String endDate=request.getParameter("endDate");
			String bankName=request.getParameter("bankName");
			
			String shopId = this.getSessionUser().getShopId();
//			formMap.put("shopId", shopId);
//			SqlUtis.convertBetweenValue(formMap, "commitTime");
//			SqlUtis.prepareSql(formMap
//					,SqlUtis.getSQL(formMap, "a."+SgSettleApply.COL_COMMIT_TIME,"commitTime", Types.DATE)
//					,SqlUtis.getSQL(formMap, "u."+RsUser.COL_REAL_NAME, realName, Types.VARCHAR,SqlUtis.LIKE)
//					,SqlUtis.getSQL(formMap, "u."+RsUser.COL_USER_NAME, userName, Types.VARCHAR,SqlUtis.LIKE)
//					);
			this.resultList = this.banksService.listSettleApply(shopId,beginDate,endDate,beginMoney,endMoney,bankName,page);
			
			JSONArray jsonArray = new JSONArray();
			
			HashMap<String, Object> hashMap;
			
			for(int i=0;i<this.resultList.size();i++){
				
				
				Map tempMap=(Map) resultList.get(i);
				
				hashMap=new HashMap<String, Object>();
				
				hashMap.put("APPLY_ID", tempMap.get("APPLY_ID")==null?"":tempMap.get("APPLY_ID"));
				hashMap.put("USER_NAME", tempMap.get("USER_NAME")==null?"":tempMap.get("USER_NAME"));
				hashMap.put("REAL_NAME", tempMap.get("REAL_NAME")==null?"":tempMap.get("REAL_NAME"));
				hashMap.put("APPLY_TYPE_NAME", tempMap.get("APPLY_TYPE_NAME")==null?"":tempMap.get("APPLY_TYPE_NAME"));
				hashMap.put("COMMIT_TIME", tempMap.get("COMMIT_TIME")==null?"":tempMap.get("COMMIT_TIME"));
				hashMap.put("AMOUNT", tempMap.get("AMOUNT")==null?"":tempMap.get("AMOUNT"));
				hashMap.put("FEE", tempMap.get("FEE")==null?"":tempMap.get("FEE"));
				hashMap.put("APPLY_STATUS_NAME", tempMap.get("APPLY_STATUS_NAME")==null?"":tempMap.get("APPLY_STATUS_NAME"));
				hashMap.put("BANK_NAME", tempMap.get("BANK_NAME")==null?"":tempMap.get("BANK_NAME"));
				hashMap.put("ACCOUNT_NAME", tempMap.get("ACCOUNT_NAME")==null?"":tempMap.get("ACCOUNT_NAME"));
				hashMap.put("BANK_NUMBER", tempMap.get("BANK_NUMBER")==null?"":tempMap.get("BANK_NUMBER"));
				hashMap.put("FINISH_TIME", tempMap.get("FINISH_TIME")==null?"":tempMap.get("FINISH_TIME"));
				
				
				
				jsonArray.add(hashMap);
				
			}
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

			jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
			
			jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
			
			jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
			
			jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());

			jsonObject.put("settleListData", jsonArray);
			
			
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		
		return this.writeJson(jsonObject);
		
		
		
	}
}
